package com.hmall.item.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/item")
public class ItemController {


    @Autowired
    private IItemService itemService;

    @GetMapping("/list")
    public PageDTO<Item> list(int page, int size) {
        Page<Item> itemPage = new Page<>(page, size);
        itemService.page(itemPage);
        List<Item> records = itemPage.getRecords();
        long total = itemPage.getTotal();
        PageDTO<Item> itemPageDTO = new PageDTO<>();
        itemPageDTO.setList(records);
        itemPageDTO.setTotal(total);
        return itemPageDTO;
    }

    @GetMapping("{id}")
    public Item getItemById(@PathVariable Long id) {
        return itemService.getById(id);
    }

    @PostMapping
    public void save(@RequestBody Item item) {
        item.setStatus(1);
        itemService.save(item);
        itemService.sendMq(JSON.toJSONString(item));
    }

    @PutMapping("/status/{id}/{status}")
    public void updateStatusById(@PathVariable Long id, @PathVariable Integer status) {
        Item item = itemService.getById(id);
        item.setStatus(status);
        itemService.updateById(item);
        itemService.sendMq(JSON.toJSONString(item));
    }

    @PutMapping
    public void updateItem(@RequestBody Item item) {
        itemService.updateById(item);
    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable Long id) {
        Item byId = itemService.getById(id);
        if (byId.getStatus() == 1) {
            throw new RuntimeException("上架的商品不能删除，请先下架！");
        }
        itemService.removeById(id);
    }

    @PutMapping("/stock/{itemId}/{num}")
    void updateStock(@PathVariable("itemId") Long itemId, @PathVariable("num") Integer num) {
        Item byId = itemService.getById(itemId);
        byId.setStock(byId.getStock()-num);
        itemService.updateById(byId);
    }

    @GetMapping("/count")
    public Integer count() {
        return itemService.count();
    }
}
